﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UserSurface;
using ApplicationCore;
using System.Diagnostics;
using ComponentFactory.Krypton.Toolkit;

namespace EnzymeLaborTool.View.Controls
{
    public partial class ExportCtrl : UserControl
    {

        private MainSurface _surface;
        private EnzymeDBDataContext _dataContext;

        public ExportCtrl()
        {
            InitializeComponent();
            exportDataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
        }

        private bool _initialized = false;
        public void Init(MainSurface ms)
        {
            if (!_initialized)
            {
                _surface = ms;
                InvalidateDataContext();
            }
        }

        public void InvalidateDataContext()
        {
            //save sorting and position
            int expPosition = experimentViewBindingSource.Position;
            var expSortCol = experimentDataGridView.SortedColumn;
            var expSortOrder = experimentDataGridView.SortOrder;

            //re-init datacontext
            _dataContext = _surface.GetDataContext();
            BindExperiment();
            //restore sorting and positon
            if (expSortCol != null)
            {
                switch (expSortOrder)
                {
                    case SortOrder.Ascending:
                        {
                            experimentDataGridView.Sort(expSortCol, ListSortDirection.Ascending);
                            break;
                        }

                    case SortOrder.Descending:
                        {
                            experimentDataGridView.Sort(expSortCol, ListSortDirection.Descending);
                            break;
                        }
                    default:
                        break;
                }
            }
            if (expPosition > -1)
                experimentViewBindingSource.Position = expPosition;
        }


        private void BindExperiment()
        {
            var q = from x in _dataContext.ExperimentViews
                    where x.Id != "? "
                    where x.Id != "EB"
                    select x;

            if (!kryptonCheckButtonShowControls.Checked)
                q = from x in q where (x.Material_Fk == null || x.Material_Fk == Guid.Empty) select x;

            if (!string.IsNullOrEmpty(kryptonTextBoxSearch.Text))
                q = from x in q where x.Id.ToLower().Contains(kryptonTextBoxSearch.Text.Trim().ToLower()) select x;

            q = from x in q orderby x.Id select x;
            experimentViewBindingSource.DataSource = q;
        }

        private void kryptonTextBoxSearch_TextChanged(object sender, EventArgs e)
        {
            BindExperiment();
        }

        private void kryptonCheckButtonShowControls_Click(object sender, EventArgs e)
        {
            BindExperiment();
        }

        private void experimentViewBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            ExperimentView current = experimentViewBindingSource.Current as ExperimentView;
            if (current != null)
            {
                kryptonHeaderGroup1.Text = "Export " + current.Id;
                EnableDisableExportControls(false);
                if (!exportLoadBackgroundWorker.IsBusy)
                    exportLoadBackgroundWorker.RunWorkerAsync();
                //  _surface.NavigateExportExperiment(current, null);
            }
        }

        private void experimentDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            try
            {
                DataGridView dgv = sender as DataGridView;
                if ((dgv.Rows[e.RowIndex].DataBoundItem as ExperimentView).Material_Fk.HasValue
                    && (dgv.Rows[e.RowIndex].DataBoundItem as ExperimentView).Material_Fk.Value != Guid.Empty)
                {
                    e.CellStyle.ForeColor = Color.Green;
                    e.CellStyle.Font = new Font(e.CellStyle.Font, FontStyle.Bold);
                }
            }
            catch (Exception)
            {
                
            }
        }

        private void exportLoadBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            if (experimentViewBindingSource.Current != null)
            {
                ExperimentView current = experimentViewBindingSource.Current as ExperimentView;
                if (current != null)
                {
                    _surface.NavigateExportExperiment(current, sender as BackgroundWorker);
                }
            }
        }

        private int lastProgress = 0;
        private void exportLoadBackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (e.ProgressPercentage - lastProgress > 3)
            {
                lastProgress = e.ProgressPercentage;
                this.exportProgressBar.Value = e.ProgressPercentage;
                this.exportProgressLabel.Text = e.UserState as string;
                this.exportProgressLabel.Update();
            }
        }

        private void exportLoadBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Debug.WriteLine("LoadData beendet");
            lastProgress = 0;
            this.exportProgressBar.Value = 0;
            this.exportProgressLabel.Text = "";
            if (e.Error == null && !e.Cancelled)
            {
                Debug.WriteLine("Starte jetzt post processing");
                //On_ExportOptionsChanged(null, null);
                exportBackgroundWorker.RunWorkerAsync();
            }
            else
            {
                EnableDisableExportControls(true);
                this.exportDataGridView.DataSource = null;
            }
        }




     

        private void exportBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker bw = sender as BackgroundWorker;
            ProgressBar.CheckForIllegalCrossThreadCalls = false;
            int decimals = (int)decimalsNumericUpDown.Value;

            if (interBatchCenteCheckButton.Checked && replicaMergeCheckButton.Checked)
            {

                e.Result = _surface.CurrenPostProcessor.ApplyExportOption(PostProcessorOption.All, decimals, bw);

            }
            else if (interBatchCenteCheckButton.Checked)
            {
                e.Result = _surface.CurrenPostProcessor.ApplyExportOption(PostProcessorOption.InterBatchCentering, decimals, bw);
            }
            else if (replicaMergeCheckButton.Checked)
            {
                e.Result = _surface.CurrenPostProcessor.ApplyExportOption(PostProcessorOption.AliquotMerge, decimals, bw);
            }
            else
            {
                e.Result = _surface.CurrenPostProcessor.ApplyExportOption(PostProcessorOption.None, decimals, bw);
            }
        }

        private void exportBackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (e.ProgressPercentage - lastProgress > 3 || e.ProgressPercentage == 0)
            {
                this.exportProgressBar.Value = e.ProgressPercentage;
                this.exportProgressLabel.Text = e.UserState as string;
                //Application.DoEvents();
                this.exportProgressLabel.Update();
            }
        }

        private void exportBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Debug.WriteLine("Post Processing beendet");

            this.exportDataGridView.DataSource = null;
            if (e.Error == null && !e.Cancelled)
            {

                this.exportDataGridView.DataSource = e.Result;
                exportDataGridView.Sort(exportDataGridView.Columns["Sample"], ListSortDirection.Ascending);
            }


            this.exportProgressBar.Value = 0;
            this.exportProgressLabel.Text = "";
            EnableDisableExportControls(true);
        }


        private void EnableDisableExportControls(bool val)
        {
            KryptonNumericUpDown.CheckForIllegalCrossThreadCalls = false;
            KryptonCheckButton.CheckForIllegalCrossThreadCalls = false;
            KryptonDataGridView.CheckForIllegalCrossThreadCalls = false;

            decimalsNumericUpDown.Enabled = val;
            interBatchCenteCheckButton.Enabled = val;
            replicaMergeCheckButton.Enabled = val;
            this.experimentDataGridView.Enabled = val;
            //this.cancelExportButton.Visible = !val;
            this.exportProgressBar.Visible = !val;


            NumericUpDown.CheckForIllegalCrossThreadCalls = true;
            KryptonCheckButton.CheckForIllegalCrossThreadCalls = true;
            DataGridView.CheckForIllegalCrossThreadCalls = true;
            Application.DoEvents();
        }
    }
}
